package org.avenger.bucky.handler;

import com.alibaba.fastjson.JSON;
import com.mongodb.DBObject;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.avenger.bucky.constant.ConfigFile;
import org.avenger.bucky.manager.MongoManager;
import org.avenger.bucky.pojo.BackupAllData;
import org.avenger.bucky.util.PropertiesUtil;

import java.io.*;
import java.util.List;

/**
 * 数据处理器
 */
public class DataHandler extends AbstractHandler {

    private static Logger log = LogManager.getLogger(DataHandler.class);

    /**
     * 将所有数据库中的集合导出到json文件
     */
    public void exportAllDataIntoJsonFile() {
        log.info("开始将所有数据库中的集合导出到json文件");

        try {
            String exportFilePath = PropertiesUtil.getValue(ConfigFile.BACKUP_ALL_DATA_PROPERTIES, "export.file.path");

            File file = new File(ConfigFile.BACKUP_ALL_DATA_JSON);
            InputStream inputStream = new FileInputStream(file);
            String text = IOUtils.toString(inputStream,"utf8");
            List<BackupAllData> backupAllDataList = JSON.parseArray(text, BackupAllData.class);

            if (null != backupAllDataList && backupAllDataList.size()>0){
                MongoManager mongoManager;
                for (BackupAllData backupAllData: backupAllDataList){
                    String databaseName = backupAllData.getDatabaseName();
                    mongoManager = new MongoManager(this.ip, Integer.parseInt(this.port), databaseName);
                    List<String> collectionList = backupAllData.getCollectionList();
                    if (null != collectionList && collectionList.size()>0){
                        for (String collectionName: collectionList){
                            log.info("开始导出数据库【" + databaseName + "】的集合【" + collectionName + "】中的文档");

                            List list = mongoManager.findByCollectionName(collectionName);
                            FileWriter fileWriter = new FileWriter(exportFilePath + "/" + databaseName + "/" + collectionName + ".json");
                            for (Object line: list){
                                fileWriter.write(JSON.toJSONString(line) + "\n");
                                fileWriter.flush();
                            }
                            fileWriter.close();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入json文件中的数据
     */
    public void importAllDataFromJsonFile() {
        log.info("开始导入json文件中的数据");

        String importFilePath = PropertiesUtil.getValue(ConfigFile.BACKUP_ALL_DATA_PROPERTIES, "export.file.path");
        File folder = new File(importFilePath);
        try {
            String[] folderArray = folder.list();
            if (null != folderArray && folderArray.length > 0){
                for (int i=0; i<folderArray.length; i++){
                    // 数据库名称
                    File databaseFileFolder = new File(importFilePath + folderArray[i]);
                    MongoManager mongoManager = new MongoManager(this.ip, Integer.parseInt(this.port), databaseFileFolder.getName());
                    String[] collectionFileArray = databaseFileFolder.list();
                    if (null != collectionFileArray && collectionFileArray.length>0){
                        for (int j=0; j<collectionFileArray.length; j++){
                            // 集合名称
                            String collectionFilename = collectionFileArray[j];
                            File collectionFile = new File(databaseFileFolder + "/" + collectionFilename);
                            // 加载json文件中的数据
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(collectionFile), "UTF-8"));//构造一个BufferedReader类来读取文件
                            String s;
                            String collectionName = null;
                            while ((s = bufferedReader.readLine()) != null) {//使用readLine方法，一次读一行
                                DBObject dbObject = (DBObject)com.mongodb.util.JSON.parse(s);
                                collectionName = collectionFilename.substring(0, collectionFilename.indexOf("."));
                                mongoManager.insertJSONString(dbObject, collectionName);
                            }
                            log.info("数据库【" + databaseFileFolder.getName() + "】的集合【" + collectionName + "】的数据导入完成");
                            bufferedReader.close();
                        }
                    }
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

}
